﻿using Simple.Tools;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Common
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
	public class PageList<T> : List<T>
	{
		public int CurrentPage { get; set; }
		public int TotalPages { get; set; }
		public int PageSize { get; set; }
		public int TotalCount { get; set; }
		public bool HasPrevious => CurrentPage > 1;
		public bool HasNext => CurrentPage < TotalPages;

		public PageList(List<T> items, int count, int pageNumber, int pageSize)
		{

			PageSize = pageSize;
			TotalCount = count;
			CurrentPage = pageNumber;
			TotalPages = count < 0 ? 0 : (int)Math.Ceiling(count / (double)pageSize);
			if (items != null)
			{
				AddRange(items);
			}
		}

		public PageList(T item)
		{
			if (item != null)
			{
				Add(item);
			}
		}
		public static async Task<PageList<T>> CreateAsync(ISugarQueryable<T> source, BaseParameter Params)
		{


			var count = source == null ? 0 : await source.CountAsync();
			if (!Params.IsPage)
			{
				var items = source == null ? null : await source.Take(BaseParameter.MaxPageSize).ToListAsync();
				return new PageList<T>(items, count, 1, count);
			}
			else
			{
				var items = source == null ? null : await source.Take(Params.PageSize).Skip((Params.PageIndex - 1) * Params.PageSize).ToListAsync();
				return new PageList<T>(items, count, Params.PageIndex, Params.PageSize);
			}
		}
		//public static async Task<PageList<T>> CreateAsync(IQueryable<T> source, BaseParameter Params)
		//{
		//    var count = source == null ? 0 : await source.CountAsync();

		//    var items = source == null ? null : await source.Skip(Params.PageSize * (Params.Current - 1)).Take(Params.PageSize).ToListAsync();

		//    return new PageList<T>(items, count, Params.Current, Params.PageSize);
		//}

		public static PageList<T> Create(List<T> source, BaseParameter Params)
		{
			var count = source == null ? 0 : source.Count;

			var items = source == null ? null : source.Skip(Params.PageSize * (Params.PageIndex - 1)).Take(Params.PageSize).ToList();

			return new PageList<T>(items, count, Params.PageIndex, Params.PageSize);
		}

		public static PageList<T> Create(T[] source, BaseParameter Params, int count)
		{
			return new PageList<T>(source.ToList(), count, Params.PageIndex, Params.PageSize);
		}
		public static PageList<T> Create(List<T> source, BaseParameter Params, int count)
		{
			return new PageList<T>(source, count, Params.PageIndex, Params.PageSize);
		}
	}
}
